define(function(require, exports, module) {
    'use strict';
    
    var rk = require('rk');
    
    require('core/widgets/input/checkbox/widget');
    var scheduleUtil = require('oa/js/schedule/asset/utils/scheduleUtil');

    $.widget('rk.calEventFilterCtrl', {
            outerObj: null,
            popupObj: null,
            typelistObj: null,
            typelistUL: null,
            _create: function(){
                var me = this;
                var elem = me.element;
                elem.click(function (){
                    window.clearTimeout(me.close_timer);
                    var parent = elem.parent();
                    me.loadHtml();
                    window.setTimeout(function(){
                        if(!me.isVisible){
                            me.popup();
                            me.updateByCookie();
                        }else{
                            me.close();
                        }                    
                    }, 80);                
                });
            },
            inited: false,
            onEventTypeChanged: function(value, isChecked){
                var me = this;
                var checkedCheckboxes = $(me.typelistUL).find('input[type="checkbox"]:checked');
                var ids = [];
                checkedCheckboxes.each(function(){
                    ids.push($(this).val());
                });
                ids = (ids.length == 0 ? '-1' : ids);//'-1' means no events displayed, null means display all.
                scheduleUtil.setDisplaySetting('scheduleTypes', ids);
                scheduleUtil.loadEvents();
            },
            onShowTaskChanged: function(value){
                //console.debug(value);
            },
            _resetHtml: function (){
                var me = this;
                var task_list = me.popupObj.find('.task_list');
                task_list.hide();
            },
            cookie_updated: false,
            updateByCookie: function(){
                var me = this;
                if(me.cookie_updated)return;

                var showTask = scheduleUtil.getDisplaySettingByCookie('showTask');
                var onlyShowUnfinishedTasks = scheduleUtil.getDisplaySettingByCookie('onlyShowUnfinishedTasks');
                var scheduleTypes = scheduleUtil.getDisplaySettingByCookie('scheduleTypes');

                if(typeof showTask != 'undefined'){
                    var btn = me.popupObj.find('.rk-show_tasks');
                    if(showTask){

                    }else{
                        btn.removeClass('display_task_check');
                        me.popupObj.find('.rk-only_undone_tasks').parent().hide();
                    }
                }
                if(typeof onlyShowUnfinishedTasks != 'undefined'){
                    var btn = me.popupObj.find('.rk-only_undone_tasks');
                    if(onlyShowUnfinishedTasks){
                        btn.removeClass('display_task_check');
                    }else{
                        btn.addClass('display_task_check');
                    }
                }
                if(typeof scheduleTypes != 'undefined'){
                    var checkboxes = me.popupObj.find('input[type="checkbox"]');
                    var json = [];
                    scheduleTypes = scheduleTypes.split(',');
                    for(var i = 0, len = scheduleTypes.length; i < len; i++){
                        var key = scheduleTypes[i] + '';
                        json[key] = true;
                    }
                    checkboxes.each(function(){
                        var colorId = $(this).val();
                        if(!json[colorId]){
                            $(this).rkCheckbox('uncheck');
                        }
                    });
                }

                me.cookie_updated = true;
            },
            loadHtml: function(){
                var me = this;
                if(me.inited){
                    me._resetHtml();
                    return;
                }
                me.outerObj = me.element;
                var p = me.outerObj.parent();
                var menuhtml = require('oa/tmpl/schedule/page/template_eventFilterMenu.tpl');//template('template_eventFilterMenu', {});
                p.append(rk.templateText(menuhtml));
                me.popupObj = p.find('.select_type');
                me.typelistUL = me.popupObj.find('ul');

                me.initHtml();
                me.listTypes();
                me.inited = true;
            },
            initHtml: function(){
                var me = this;
                var show_task_types = me.popupObj.find('.show_task_types');
                var task_list = me.popupObj.find('.task_list');
                var show_task_selector_btn = me.popupObj.find('.show_task_selector_btn');
                
                // me.outerObj.bind('mouseleave', function(){
                //     me.close_timer = window.setTimeout(function(){ me.close(); }, 8000);
                // });
                me.popupObj.bind('mousemove', function(){
                    window.clearTimeout(me.close_timer);
                });
                $(document.body).bind('mousedown', function(){
                    me.close_timer = window.setTimeout(function(){ me.close(); }, 200);
                });
                me.popupObj.bind('mouseup', function(){
                    window.clearTimeout(me.close_timer);
                });
                $(me.typelistUL).on('click', 'a', function(e){
                    var checkbox = $(this).find('input:checkbox');
                    checkbox.rkCheckbox('toggle');
                    var value = checkbox.val();
                    var isChecked = checkbox.rkCheckbox('isChecked');
                    me.onEventTypeChanged(value, isChecked);
                });
                //显示筛选大菜单
                var showTasks_btn = me.popupObj.find('.rk-show_tasks');
                var only_undone_tasks_btn = me.popupObj.find('.rk-only_undone_tasks');

                me.popupObj.find('.rk-show_tasks').parent().bind('click',function(){
                    window.clearTimeout(me.close_timer);
                    var btn = $(this).find('.rk-show_tasks');
                    if(!btn.hasClass('display_task_check')){
                        btn.addClass('display_task_check');
                        scheduleUtil.setDisplaySetting('showTask', true);
                        only_undone_tasks_btn.parent().show();
                    }else{
                        btn.removeClass('display_task_check');
                        scheduleUtil.setDisplaySetting('showTask', false);
                        only_undone_tasks_btn.parent().hide();
                    }
                    //scheduleUtil.reRenderEvents();
                    scheduleUtil.loadEvents();//now is ajax re-load, by design!
                });
                me.popupObj.find('.rk-only_undone_tasks').parent().bind('click',function(){
                    window.clearTimeout(me.close_timer);
                    var btn = $(this).find('.rk-only_undone_tasks');
                    if(!btn.hasClass('display_task_check')){
                        btn.addClass('display_task_check');
                        scheduleUtil.setDisplaySetting('onlyShowUnfinishedTasks', false);
                    }else{
                        btn.removeClass('display_task_check');
                        scheduleUtil.setDisplaySetting('onlyShowUnfinishedTasks', true);
                    }
                    //scheduleUtil.reRenderEvents();
                    scheduleUtil.loadEvents();
                });
            },
            _getColorArray: function(oldArray){
                var newArray = [];
                var default_color;
                for(var i = 0, len = oldArray.length; i < len; i++){
                    var color = oldArray[i];
                    color = $.extend({}, color);
                    if(color.color != 'schedule_none'){
                        newArray.push(color);
                    }else{
                        default_color = color;
                    }
                }
                if(default_color)
                newArray.push(default_color);
                return newArray;
            },
            listTypes: function(){
                var me = this;
                scheduleUtil.fetchColorList(function(data){
                    var colorArray = data;
                    colorArray = me._getColorArray(colorArray);
                    var listhtml = '';//<ul>';
                    for(var i = 0, len = colorArray.length; i < len; i++){
                        var def = colorArray[i];
                        listhtml = listhtml + '<li><a href="javascript:void(0)">'+
                                                    '<input id="test_checkbox'+i+'" type="checkbox" checked value="'+def.id+'" value-color="'+def.color+'" checked-css="'+def.color+'_check" unchecked-css="'+def.color+'_normal"/>'+
                                                    '<span class="text">'+def.name+'</span></a></li>';
                    }
                    me.typelistUL.html(listhtml);
                    
                    $(me.typelistUL).find('input[type="checkbox"]').rkCheckbox({
                            noClick: true//no click listening
                    });
                });
            },
            isVisible: false,
            popup: function (){
                var me = this;
                me.popupObj.css({'top': 15, 'left': -30}).show();//hard code for css offset
                me.isVisible = true;
            },
            close_timer: null,
            close: function (){
                var me = this;
                me.popupObj.hide();
                me.isVisible = false;
            },
            select: function(val){

            },
            getConditions: function(){
                var me = this;
                var types = [];
                me.typelistUL.find('input:checked').each(function(){
                    var ipt = $(this);
                    types.push($(ipt).attr('value'));
                });
                var item = me.popupObj.find('.task_list').find('.check_task');
                var show_type = item.attr('data-show');
                return {
                    types: types,
                    show: show_type
                }
            }
    });
});